package lxt.action.core;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	private String loginPage;
	private String homePage;

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();

		String requestUri = req.getRequestURI();
		String ctxPath = req.getContextPath() + "/";

		try {
			Object user = session.getAttribute("user");
			if (user != null || requestUri.substring(ctxPath.length()).equals(loginPage)) {
				chain.doFilter(request, response);
				return;
			} else {
				PrintWriter out = response.getWriter();
				out.println("<html>");
				out.println("<script type=\"text/javascript\">");
				out.println("window.open('" + homePage + loginPage + "?f=sessLose','_top')");
				out.println("</script>");  
				out.println("</html>");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init(FilterConfig cfg) throws ServletException {
		// 获取配置信息
		loginPage = cfg.getInitParameter("LOGIURL");
		homePage = cfg.getInitParameter("HOMEURL");
		if (null == loginPage || null == homePage) {
			throw new ServletException("ERROR:No Home or Login Page found!");
		}
	}

}
